import json
import uuid

from django.shortcuts import render
from django.views import View
from django.utils.decorators import method_decorator

from utils.verifyUtil import verfy_params
from utils.resFormatUyil import FormatResponse
from commodity.models import Commodity,CommodityOptions
from order.models import Order
from apps.user.models import User
from qqmall.settings import alipay

# Create your views here.


# 支付功能
class OrderView(View):
    # 订单的生成功能
    @method_decorator(verfy_params('id','num','option_id','subject'))
    def post(self,request):
        '''

        :param request:
        :return:
        id:商品对应的id
        num:购买商品的数量
        option_id:带有金额的商品选项
        subject:商品信息
        '''
        # 获取传入的相关参数
        commodity_id = request.POST.get('id')
        num = request.POST.get('num')
        option_id = request.POST.get('option_id')
        subject = request.POST.get('subject')

        # 生成订单号
        order_no = str(uuid.uuid4())

        # 获取用户信息，若用户没有登录则返回限制访问
        user_query = User.objects.filter(status=0,email=request.email)
        if not user_query:
            return FormatResponse(status='ACCESS_RESTRICTION').res()
        user_id = user_query[0].id

        # 通过商品选项的id获取商品选项
        option = CommodityOptions.objects.filter(status=0,id=option_id)
        if not option:
            return FormatResponse(status='PARAM_ERROR').res()
        # 修改数据库的库存数量
        option[0].inventory = option[0].inventory - int(num)
        option[0].save()
        # 获取商品价格
        money = option[0].price * int(num)
        # 生成订单信息
        Order.objects.create(order_no=order_no, money=money, subject=subject, commodity_id=commodity_id,
                             user_id=user_id)

        order_param = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_no,
            total_amount=money,
            subject=subject,
            return_url='http://127.0.0.1:8001/order/alipay/'  # 回调地址，当支付成功后，跳转到这个地址
        )

        # 构造支付url:支付宝网关 + 订单参数
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_param

        return FormatResponse().res()